package org.jumiz.dbview.own.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class SqlScriptRunner implements CommandLineRunner {

    @Autowired
    private DatabaseClient databaseClient;

    @Override
    public void run(String... args) throws Exception {
        ClassPathResource resource = new ClassPathResource("schema.sql");
        String sqls = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
        Flux.fromArray(sqls.split(";"))
                .subscribe(sql ->
                        Mono.from(databaseClient.getConnectionFactory().create())
                                .flatMap(connection -> Mono.from(connection.createStatement(sql).execute()))
                                .then()
                                .block());
    }

}
